//
//  YLUIColorExtension.swift
//  YiZhangGui
//
//  Created by Fexerlear on 2019/2/21.
//  Copyright © 2019 Mac. All rights reserved.
//

import UIKit

extension UIColor {
    
    // 初始化器：从十六进制字符串创建颜色
    convenience init(hexString: String) {
        self.init(hexString: hexString, withAlpha: 1.0) // 默认 alpha 为 1.0
    }
    
    // 初始化器：从十六进制字符串和 alpha 值创建颜色
    convenience init(hexString string: String, withAlpha alpha: CGFloat) {
        var hex = string.hasPrefix("#") ? String(string.dropFirst()) : string
        
        guard hex.count == 3 || hex.count == 6 else {
            self.init(white: 1.0, alpha: 0.0) // 返回透明白色
            return
        }
        
        // 如果是 3 位数的十六进制，转换为 6 位数
        if hex.count == 3 {
            hex = hex.enumerated().map { String(repeating: $1, count: 2) }.joined()
        }
        
        guard let intCode = Int(hex, radix: 16) else {
            self.init(white: 1.0, alpha: 0.0) // 返回透明白色
            return
        }
        
        self.init(
            red:   CGFloat((intCode >> 16) & 0xFF) / 255.0,
            green: CGFloat((intCode >> 8) & 0xFF) / 255.0,
            blue:  CGFloat(intCode & 0xFF) / 255.0,
            alpha: alpha
        )
    }
    
    // 从颜色生成 UIImage
    func imageFromColor(viewSize: CGSize) -> UIImage {
        let rect = CGRect(origin: .zero, size: viewSize)
        
        UIGraphicsBeginImageContext(rect.size)
        
        guard let context = UIGraphicsGetCurrentContext() else { return UIImage() }
        
        context.setFillColor(self.cgColor)
        context.fill(rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext() // 结束图形上下文
        
        return image ?? UIImage() // 返回生成的图片
    }
}
